﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Security.Server;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

namespace LightSwitchApplication
{
    public partial class ApplicationDataService
    {
        partial void ImagesSet_Inserting(Images entity)
        {
            // Convert ByteStream to Image
            // http://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
            MemoryStream ImageStream = new MemoryStream(entity.Picture);
            Image image = Image.FromStream(ImageStream);

            // Resize Image to max 250x250 Pixel, preserve aspect ratio
            // http://www.codeproject.com/Articles/191424/Resizing-an-Image-On-The-Fly-using-NET
            int maxWidth = 250;
            int maxHeight = 250;

            int originalWidth = image.Width;
            int originalHeight = image.Height;
            float percentWidth = (float)maxWidth / (float)originalWidth;
            float percentHeight = (float)maxHeight / (float)originalHeight;
            float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
            
            int newWidth = (int)(originalWidth * percent);
            int newHeight = (int)(originalHeight * percent);

            // Save new dimensions
            entity.Width = newWidth;
            entity.Height = newHeight;

            // Save new image
            Image newImage = new Bitmap(newWidth, newHeight);
            using (Graphics graphicsHandle = Graphics.FromImage(newImage))
            {
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
            }

            // Convert Image to ByteStream
            MemoryStream ResultImageStream = new MemoryStream();
            newImage.Save(ResultImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

            // Save Image and ImageSize
            entity.Picture = ResultImageStream.ToArray();
            entity.SizeByte = entity.Picture.Length;

        }
    }
}
